package com.wyzz.hr.action;

import java.util.*;
import javax.servlet.http.HttpServletRequest;

import com.wyzz.hr.base.DWRUtil;
import com.wyzz.hr.bo.IEmpBenefitBo;
import com.wyzz.hr.bo.IEmpSalaryAcctBo;
import com.wyzz.hr.bo.IEmpSalaryAcctitemsBo;
import com.wyzz.hr.bo.IEmpSalaryAcctversionBo;
import com.wyzz.hr.bo.ISalaryPaidBo;
import com.wyzz.hr.bo.ISalaryconfBo;
import com.wyzz.hr.pojo.Empsalaryacct;
import com.wyzz.hr.pojo.Empsalaryacctitems;
import com.wyzz.hr.pojo.Empsalaryacctversion;
import com.wyzz.hr.pojo.Empsalaryconfig;
import com.wyzz.hr.pojo.Empsalarydatadef;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.Interpreter;
import com.wyzz.hr.util.StringUtil;

public class UpdateEmpsalaryacct extends CompAction {

	public UpdateEmpsalaryacct() {
		empsalaryacctversion = new Empsalaryacctversion();
		viewType = "0";
		searchOrExport = null;
	}

	public String updateInit() throws Exception {
		IEmpSalaryAcctversionBo esavBo = (IEmpSalaryAcctversionBo) getBean("empsalaryacctversionBo");
		empsalaryacctversion = esavBo.loadObject(id, new String[0]);
		if (empsalaryacctversion == null) {
			addActionError("\u85AA\u8D44\u5E10\u5957\u7248\u672C\u4E0D\u5B58\u5728\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5\uFF01");// 薪资帐套版本不存在
			// ，
			// 请检查后重试
			// ！
			return "success";
		}
		IEmpSalaryAcctBo esaBo = (IEmpSalaryAcctBo) getBean("empsalaryacctBo");
		empsalaryacct = esaBo.loadObject(empsalaryacctversion.getEsavEsac()
				.getId(), new String[0]);
		IEmpSalaryAcctitemsBo esaiBo = (IEmpSalaryAcctitemsBo) getBean("empsalaryacctitemsBo");
		List esaiList = esaiBo.getItemsByAcctversion(id);
		if ("export".equals(searchOrExport)) {
			getClass();
			return downloadToExcel(esaiList, "OSalaryAcctitems",
					outmatchModelId);
		}
		if (esaiList.size() == 0) {// 薪资帐套版本无任何项目，不能修改！
			addActionError("\u85AA\u8D44\u5E10\u5957\u7248\u672C\u65E0\u4EFB\u4F55\u9879\u76EE\uFF0C\u4E0D\u80FD\u4FEE\u6539\uFF01");
			return "success";
		}
		acctitemNos = esaiList.size();
		dataDefIds = new String[acctitemNos];
		dataTypes = new Integer[acctitemNos];
		dataIsCalcs = new Integer[acctitemNos];
		dataCalcs = new String[acctitemNos];
		dataRoundings = new Integer[acctitemNos];
		dataNames = new String[acctitemNos];
		for (int i = 0; i < acctitemNos; i++) {
			Empsalaryacctitems item = (Empsalaryacctitems) esaiList.get(i);
			dataDefIds[i] = item.getEsaiEsdd().getEsddId();
			dataTypes[i] = item.getEsaiEsdd().getEsddDataType();
			dataIsCalcs[i] = item.getEsaiDataIsCalc();
			dataCalcs[i] = item.getEsaiDataCalc();
			dataRoundings[i] = item.getEsaiDataRounding();
			dataNames[i] = item.getEsaiEsdd().getEsddName();
		}

		if (empsalaryacctversion.getEsavValidTo() != null)
			viewType = "1";
		String flag = getRequest().getParameter("flag");
		if ("copy".equals(flag))
			empsalaryacct.setEsacName((new StringBuilder()).append(
					empsalaryacct.getEsacName()).append("(\u590D\u4EF6)")
					.toString());
		return "success";
	}

	public String execute() throws Exception {
		if (empsalaryacct == null) {// 请设置帐套名称和描述！
			addActionError("\u8BF7\u8BBE\u7F6E\u5E10\u5957\u540D\u79F0\u548C\u63CF\u8FF0\uFF01");
			return "input";
		}
		empsalaryacct.setEsacName(empsalaryacct.getEsacName().trim());
		String info = commonCheck();
		if (!info.equals("SUCC")) {
			addErrorInfo(info);
			return "input";
		}
		IEmpSalaryAcctversionBo esavBo = (IEmpSalaryAcctversionBo) getBean("empsalaryacctversionBo");
		Map oldMap = esavBo.getOldAcctItems(empsalaryacctversion.getId());
		List newItems = getNewAcctItems();
		ISalaryPaidBo salaryPaidBo = (ISalaryPaidBo) SpringBeanFactory
				.getBean("salaryPaidBo");
		List salaryPayList = salaryPaidBo
				.getSalaryPaidbyEsav(empsalaryacctversion.getId());
		IEmpBenefitBo empbenefitBo = (IEmpBenefitBo) SpringBeanFactory
				.getBean("empbenefitBo");
		List planList = empbenefitBo.getBenefitPlanByEsav(empsalaryacctversion
				.getId());
		if (salaryPayList.size() > 0 || planList.size() > 0) {
			int hasDiff = checkDiff(oldMap, newItems);
			if (hasDiff == 1) {
				addErrorInfo("\u5E10\u5957\u6709\u91CD\u5927\u6539\u53D8\uFF0C\u66F4\u65B0\u5C06\u5BFC\u81F4\u85AA\u8D44\u53D1\u653E\u5386\u53F2\u6570\u636E\u5F02\u5E38\uFF0C\u8BF7\u60A8\u53E6\u5B58\u4E3A\u65B0\u7248\u672C\uFF01");//帐套有重大改变，更新将导致薪资发放历史数据异常，请您另存为新版本！
				return "input";
			}
			if (hasDiff == 0) {
				salaryPaidBo.shuffleSalaryPay(salaryPayList, oldMap, newItems);
				empbenefitBo.shuffleBenefitPlan(planList, oldMap, newItems);
			}
		}
		ISalaryconfBo salaryconfBo = (ISalaryconfBo) getBean("salaryconfBo");
		List salaryconfigList = salaryconfBo.changeSalaryConfig(
				empsalaryacctversion.getId(), oldMap, newItems);
		empsalaryacctversion.setEsavEsac(empsalaryacct);
		empsalaryacctversion.setEsavLastChangeBy(getCurrentEmpNo());
		esavBo.updateAcctVersion(empsalaryacctversion, newItems,
				salaryconfigList, salaryPayList, planList);
		addActionMessage((new StringBuilder()).append("\u4FEE\u6539").append(//修改
				empsalaryacct.getEsacName()).append("\u6210\u529F\u3002")//成功。
				.toString());
		empsalaryacct = null;
		empsalaryacctversion = null;
		dataDefIds = null;
		dataIsCalcs = null;
		dataCalcs = null;
		dataRoundings = null;
		return "success";
	}

	public String geneNewVersion() throws Exception {
		if (empsalaryacct == null) {
			addActionError("\u8BF7\u8BBE\u7F6E\u5E10\u5957\u540D\u79F0\u548C\u63CF\u8FF0\uFF01");
			return "input";
		}
		String info = commonCheck();
		if (!info.equals("SUCC")) {
			addErrorInfo(info);
			return "input";
		}
		Date today = DateUtil.convDateTimeToDate(new Date());
		if (DateUtil
				.dateDiff(today, empsalaryacctversion.getEsavValidFrom(), 5) == 0) {
			addActionError("\u60A8\u4ECA\u5929\u5DF2\u5B58\u8FC7\u85AA\u8D44\u5E10\u5957\u7248\u672C\uFF0C\u540C\u4E00\u5E10\u5957\u4E00\u5929\u53EA\u80FD\u5B58\u4E00\u4E2A\u65B0\u7248\u672C\uFF01");
			return "input";
		} else {
			IEmpSalaryAcctversionBo esavBo = (IEmpSalaryAcctversionBo) getBean("empsalaryacctversionBo");
			Map oldMap = esavBo.getOldAcctItems(empsalaryacctversion.getId());
			List newItems = getNewAcctItems();
			ISalaryconfBo salaryconfBo = (ISalaryconfBo) getBean("salaryconfBo");
			List salaryconfigList = salaryconfBo.changeSalaryConfig(
					empsalaryacctversion.getId(), oldMap, newItems);
			empsalaryacctversion.setEsavEsac(empsalaryacct);
			empsalaryacctversion.setEsavLastChangeBy(getCurrentEmpNo());
			esavBo.updateAcctVersion(empsalaryacctversion, newItems,
					salaryconfigList);
			addActionMessage((new StringBuilder()).append(
					"\u53E6\u5B58\u5E10\u5957").append(
					empsalaryacct.getEsacName()).append(
					"\u7684\u65B0\u7248\u672C\u6210\u529F\u3002").toString());
			empsalaryacct = null;
			empsalaryacctversion = null;
			dataDefIds = null;
			dataIsCalcs = null;
			dataCalcs = null;
			dataRoundings = null;
			return "success";
		}
	}

	private String commonCheck() {
		IEmpSalaryAcctBo esaBo = (IEmpSalaryAcctBo) getBean("empsalaryacctBo");
		if (esaBo.searchAcctNames(this.empsalaryacct.getEsacName(),
				this.empsalaryacct.getId())) {
			return "帐套名称不允许重复！";
		}

		if (this.empsalaryacctversion.getEsavValidTo() != null) {
			return "此帐套为历史帐套，请在最新帐套版本上修改";
		}

		for (int i = this.dataDefIds.length; i > 0; --i) {
			if (this.dataDefIds[(i - 1)] == null)
				continue;
			if (this.dataDefIds[(i - 1)].length() != 0) {
				this.acctitemNos = i;
				break;
			}
		}

		Boolean hasBasicSalary = Boolean.valueOf(false);
		Boolean hasIncomeBfTax = Boolean.valueOf(false);
		Boolean hasTax = Boolean.valueOf(false);
		Boolean hasIncomeAfTax = Boolean.valueOf(false);
		Interpreter interpreter = new Interpreter();
		for (int i = 0; i < this.acctitemNos; ++i)
			if (this.dataTypes[i].intValue() == 1) {
				hasBasicSalary = Boolean.valueOf(true);
			} else if (this.dataTypes[i].intValue() == 8) {
				hasIncomeBfTax = Boolean.valueOf(true);
			} else if (this.dataTypes[i].intValue() == 18) {
				hasTax = Boolean.valueOf(true);
			} else {
				if (this.dataTypes[i].intValue() != 19)
					continue;
				hasIncomeAfTax = Boolean.valueOf(true);
			}
		if (hasBasicSalary.booleanValue() != true)
			return "项目种类不完整，帐套必须包含“基本工资”！";
		if (hasIncomeBfTax.booleanValue() != true)
			return "项目种类不完整，帐套必须包含“税前收入”！";
		if (hasTax.booleanValue() != true)
			return "项目种类不完整，帐套必须包含“所得税”！";
		if (hasIncomeAfTax.booleanValue() != true)
			return "项目种类不完整，帐套必须包含“税后收入”！";

		StringBuffer formularError = new StringBuffer();
		for (int i = 0; i < this.acctitemNos; ++i) {
			if (this.dataIsCalcs[i].intValue() == 2) {
				String info = interpreter.formulaValidate(this.dataCalcs[i],
						new Empsalaryconfig());
				if (!info.equals("SUCC")) {
					formularError.append("您输入的公式 A" + (i + 1) + "不合法：" + info);
				}
			}
		}
		if (formularError.toString().length() > 0) {
			return formularError.toString();
		}

		return "SUCC";
	}

	private List getNewAcctItems() {
		List returnList = new ArrayList();
		for (int i = 0; i < acctitemNos; i++) {
			if (dataDefIds[i] == null || dataDefIds[i].length() == 0 || i >= 48)
				continue;
			Empsalaryacctitems empsalaryacctitem = new Empsalaryacctitems();
			empsalaryacctitem.setEsaiEsdd(new Empsalarydatadef(dataDefIds[i]));
			empsalaryacctitem.setEsaiDataIsCalc(dataIsCalcs[i]);
			if (dataCalcs[i] != null)
				empsalaryacctitem.setEsaiDataCalc(dataCalcs[i].replaceAll(" ",
						"").toUpperCase());
			empsalaryacctitem.setEsaiDataRounding(dataRoundings[i]);
			empsalaryacctitem.setEsaiDataSeq(Integer.valueOf(i + 1));
			empsalaryacctitem.setEsaiEsav(empsalaryacctversion);
			returnList.add(empsalaryacctitem);
		}

		return returnList;
	}

	private int checkDiff(Map oldMap, List newItems) {
		int hasDiff = -1;
		String dataDefId = new String();
		HashMap tempMap = (HashMap) ((HashMap) oldMap).clone();
		for (int i = 0; i < newItems.size(); i++) {
			dataDefId = ((Empsalaryacctitems) newItems.get(i)).getEsaiEsdd()
					.getEsddId();
			Integer value = (Integer) tempMap.get(dataDefId);
			if (value == null)
				return 1;
			if (value.intValue() != i)
				hasDiff = 0;
			tempMap.remove(dataDefId);
		}

		if (!tempMap.isEmpty())
			hasDiff = 1;
		return hasDiff;
	}

	public String pageGetDiff(String acctversionId, String pageDataDefIds[]) {
		if (!"HR".equals(DWRUtil.checkAuth("updateesainit", "execute"))) {
			return StringUtil
					.message(this.msgNoAuth, new Object[] { "noauth" });
		}
		ISalaryPaidBo salaryPaidBo = (ISalaryPaidBo) SpringBeanFactory
				.getBean("salaryPaidBo");
		if (salaryPaidBo.hasSalaryPayByAcctVersion(acctversionId) == 0) {
			return StringUtil.message(this.msgAcctUpdConf,
					new Object[] { "WARNING" });
		}
		IEmpSalaryAcctversionBo esavBo = (IEmpSalaryAcctversionBo) getBean("empsalaryacctversionBo");
		Map oldMap = esavBo.getOldAcctItems(acctversionId);

		for (int i = pageDataDefIds.length; i > 0; --i) {
			if (pageDataDefIds[(i - 1)] == null)
				continue;
			if (pageDataDefIds[(i - 1)].length() != 0) {
				this.acctitemNos = i;
				break;
			}
		}
		int hasDiff = -1;

		for (int i = 0; i < this.acctitemNos; ++i) {
			Integer value = (Integer) oldMap.get(pageDataDefIds[i]);

			if (value == null) {
				return StringUtil.message(this.msgAcctUpdErr,
						new Object[] { "upderr" });
			}

			if (value.intValue() != i)
				hasDiff = 0;
			oldMap.remove(pageDataDefIds[i]);
		}

		if (!oldMap.isEmpty()) {
			return StringUtil.message(this.msgAcctUpdErr,
					new Object[] { "upderr" });
		}
		if (hasDiff == 0) {
			return StringUtil.message(this.msgAcctUpdConfPay,
					new Object[] { "WARNING" });
		}
		return StringUtil.message(this.msgAcctUpdConf,
				new Object[] { "WARNING" });
	}

	public Empsalaryacct getEmpsalaryacct() {
		return empsalaryacct;
	}

	public void setEmpsalaryacct(Empsalaryacct empsalaryacct) {
		this.empsalaryacct = empsalaryacct;
	}

	public Empsalaryacctversion getEmpsalaryacctversion() {
		return empsalaryacctversion;
	}

	public void setEmpsalaryacctversion(
			Empsalaryacctversion empsalaryacctversion) {
		this.empsalaryacctversion = empsalaryacctversion;
	}

	public List getSalaryConfigFormList() {
		return salaryConfigFormList;
	}

	public void setSalaryConfigFormList(List salaryConfigFormList) {
		this.salaryConfigFormList = salaryConfigFormList;
	}

	public String getUpdateFlag() {
		return updateFlag;
	}

	public void setUpdateFlag(String updateFlag) {
		this.updateFlag = updateFlag;
	}

	public List getEsaiList() {
		return esaiList;
	}

	public void setEsaiList(List esaiList) {
		this.esaiList = esaiList;
	}

	public String[] getDataDefIds() {
		return dataDefIds;
	}

	public void setDataDefIds(String dataDefIds[]) {
		this.dataDefIds = dataDefIds;
	}

	public Integer[] getDataTypes() {
		return dataTypes;
	}

	public void setDataTypes(Integer dataTypes[]) {
		this.dataTypes = dataTypes;
	}

	public Integer[] getDataIsCalcs() {
		return dataIsCalcs;
	}

	public void setDataIsCalcs(Integer dataIsCalcs[]) {
		this.dataIsCalcs = dataIsCalcs;
	}

	public String[] getDataCalcs() {
		return dataCalcs;
	}

	public void setDataCalcs(String dataCalcs[]) {
		this.dataCalcs = dataCalcs;
	}

	public Integer[] getDataRoundings() {
		return dataRoundings;
	}

	public void setDataRoundings(Integer dataRoundings[]) {
		this.dataRoundings = dataRoundings;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getViewType() {
		return viewType;
	}

	public void setViewType(String viewType) {
		this.viewType = viewType;
	}

	public String[] getDataNames() {
		return dataNames;
	}

	public void setDataNames(String dataNames[]) {
		this.dataNames = dataNames;
	}

	public Integer getHasDiff() {
		return hasDiff;
	}

	public void setHasDiff(Integer hasDiff) {
		this.hasDiff = hasDiff;
	}

	public String getOutmatchModelId() {
		return outmatchModelId;
	}

	public void setOutmatchModelId(String outmatchModelId) {
		this.outmatchModelId = outmatchModelId;
	}

	public String getSearchOrExport() {
		return searchOrExport;
	}

	public void setSearchOrExport(String searchOrExport) {
		this.searchOrExport = searchOrExport;
	}

	private static final long serialVersionUID = 1L;
	private Empsalaryacct empsalaryacct;
	private Empsalaryacctversion empsalaryacctversion;
	private String dataDefIds[];
	private Integer dataTypes[];
	private Integer dataIsCalcs[];
	private String dataCalcs[];
	private Integer dataRoundings[];
	private String dataNames[];
	private int acctitemNos;
	private String updateFlag;
	List esaiList;
	private List salaryConfigFormList;
	private String id;
	private Integer hasDiff;
	private String viewType;
	private String outmatchModelId;
	public final String outputIoName = "OSalaryAcctitems";
	private String searchOrExport;
}
